import React, { useState } from 'react';
import { Button, message, Progress } from 'antd';
import { EyeOutlined, EyeInvisibleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import Modals from '@/components/modals/Modals';
import { Input, Steps, Select, TextArea } from '@/components/eai-design';
import nl2sqlService from '@/api/services/nl2sqlService';
import { TestConnectionRequest, GetDatabasesRequest, GetTablesRequest, CreateConnectionRequest, UpdateConnectionRequest, TaskProgressResponse } from '@/types/nl2sql/type';
import { useParams } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import { ConnectionInfo } from '@/types/nl2sql/type'; // 导入 ConnectionInfo 类型
import { hashStr } from '@/utils/common';
import { useTaskProgress } from '@/hooks/useTaskProgress';

// 配置：是否启用进度版数据库连接创建与更新
const ENABLE_PROGRESS_MODE = true;

// 测试数据常量
const TEST_DATA = {
  displayName: '测试数据库连接',
  description: '用于调试的测试数据库连接',
  dbType: 'mysql',
  host: '172.30.232.143',
  port: '18088',
  username: 'admin',
  password: '123456',
} as const;

// 空表单数据
const EMPTY_FORM_DATA: FormData = {
  displayName: '',
  description: '',
  dbType: 'mysql',
  host: '',
  port: '',
  username: '',
  password: '',
  database: '',
  selectedDatabase: '',
  selectedTable: [],
};

interface DatabaseAccessModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  connections?: ConnectionInfo[];
  connection?: ConnectionInfo | null; // 添加连接信息，用于编辑模式
  handleConnectionSelect?: (connection: ConnectionInfo | null) => void;
}

interface FormData {
  displayName: string;
  description: string;
  dbType: string;
  host: string;
  port: string;
  username: string;
  password: string;
  database: string;
  selectedDatabase: string;
  selectedTable: string[];
}

// 模态框状态枚举
enum ModalState {
  FORM = 'form',           // 表单填写状态
  LOADING = 'loading',     // 加载状态
  SUCCESS = 'success',     // 成功状态
  FAILED = 'failed'        // 失败状态
}

const DatabaseAccessModal: React.FC<DatabaseAccessModalProps> = ({
  open,
  onClose,
  onSuccess,
  connections,
  connection,
  handleConnectionSelect,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [showPassword, setShowPassword] = useState(false);
  const [modalState, setModalState] = useState<ModalState>(ModalState.FORM);
  const [progressValue, setProgressValue] = useState(0);
  const [errorMessage, setErrorMessage] = useState('');

  // 进度版相关状态
  const [taskId, setTaskId] = useState<string>('');

  const {
    progress,
    isCompleted: isTaskCompleted,
    errorMessage: taskErrorMessage,
    isPolling,
    startPolling,
    stopPolling,
    reset: resetTaskProgress,
  } = useTaskProgress({
    onSuccess: async (data) => {
      setModalState(ModalState.SUCCESS);
      message.success(isEditMode ? '更新成功' : '接入成功');
      taskId && await nl2sqlService.deleteTaskProgress(taskId);
      handleClose();
      onSuccess?.();
    },
    onError: async (data) => {
      setModalState(ModalState.FAILED);
      setErrorMessage(data.ret_message || '任务执行失败');
      taskId && await nl2sqlService.deleteTaskProgress(taskId);
    },
    onProgress: (progressValue) => {
      setProgressValue(progressValue);
    },
    pollingInterval: 2000,
    maxRetries: 5,
  });

  const { appId } = useParams() as { appId: string };
  const { groupId } = useUserInfo();

  // 开始进度轮询
  const startProgressPolling = (taskId: string) => {
    startPolling(taskId);
  };

  // 判断是否为编辑模式
  const isEditMode = !!connection;

  // 根据模式初始化表单数据
  const getInitialFormData = (): FormData => {
    if (isEditMode) {
      // 编辑模式：使用空数据，不填入测试数据
      return { ...EMPTY_FORM_DATA };
    } else {
      // 新建模式：使用测试数据
      return {
        ...EMPTY_FORM_DATA,
        selectedDatabase: '',
        selectedTable: [],
      };
    }
  };

  const [formData, setFormData] = useState<FormData>(getInitialFormData());
  const [databases, setDatabases] = useState<string[]>([]);
  const [tables, setTables] = useState<string[]>([]);
  const [connectionError, setConnectionError] = useState('');

  // 当 connection 变化时，更新表单数据（编辑模式）
  React.useEffect(() => {
    if (connection && isEditMode) {
      // 从 connection 中提取表名列表
      const tableNames = connection.table_simple_infos?.map(table => table.table_name) || [];

      setFormData({
        displayName: connection.display_name || '',
        description: connection.description || '',
        dbType: connection.config?.db_type || 'mysql',
        host: connection.config?.host || '',
        port: connection.config?.port?.toString() || '',
        username: connection.config?.username || '',
        password: connection.config?.password || '',
        database: connection.config?.database || '',
        selectedDatabase: connection.config?.database || '',
        selectedTable: tableNames,
      });

      // 如果有数据库信息，设置数据库和表列表
      if (connection.config?.database) {
        setDatabases([connection.config.database]);
        setTables(tableNames);
      } else {
        // 清空数据库和表列表，让用户重新获取
        setDatabases([]);
        setTables([]);
      }
    }
  }, [connection, isEditMode]);

  // 数据库类型选项
  const dbTypeOptions = [
    { label: 'MySQL', value: 'mysql' },
    { label: 'PostgreSQL', value: 'postgresql' },
    // { label: 'SQLite', value: 'sqlite' },
    { label: 'Oracle', value: 'oracle' },
    // { label: 'SQL Server', value: 'sqlserver' },
  ];

  // 测试连接
  const { runAsync: testConnection, loading: testLoading } = useRequest(
    async (data: TestConnectionRequest) => {
      return await nl2sqlService.testConnection(data);
    },
    {
      manual: true,
      onError: (error) => {
        setConnectionError('连接超时,请检测输入信息是否正确后再试');
        // message.error('连接失败');
      },
    }
  );

  // 获取数据库列表
  const { runAsync: getDatabases, loading: getDbLoading } = useRequest(
    async (data: GetDatabasesRequest) => {
      return await nl2sqlService.getDatabases(data);
    },
    {
      manual: true,
      onSuccess: (data) => {
        setDatabases(data);
        setConnectionError('');
      },
      onError: (error) => {
        setConnectionError('获取数据库列表失败');
        message.error('获取数据库列表失败');
      },
    }
  );

  // 获取表列表
  const { runAsync: getTables, loading: getTableLoading } = useRequest(
    async (data: GetTablesRequest) => {
      return await nl2sqlService.getTables(data);
    },
    {
      manual: true,
      onSuccess: (data) => {
        setTables(data);
      },
      onError: (error) => {
        message.error('获取表列表失败');
      },
    }
  );

  // 创建数据库连接
  const { runAsync: createConnection, loading: createLoading } = useRequest(
    async (data: CreateConnectionRequest) => {
      if (ENABLE_PROGRESS_MODE) {
        // 进度版模式
        const response = await nl2sqlService.createConnectionProgress(data);
        setTaskId(response.task_id);
        startProgressPolling(response.task_id);
        return response;
      } else {
        // 普通模式
        return await nl2sqlService.createConnection(data);
      }
    },
    {
      manual: true,
      onSuccess: (data) => {
        if (!ENABLE_PROGRESS_MODE) {
          // 普通模式下的成功处理
          setModalState(ModalState.SUCCESS);
          message.success('接入成功');
          handleClose();
          onSuccess?.();
        }
        // 进度版模式下的成功处理在轮询函数中处理
      },
      onError: (error) => {
        if (!ENABLE_PROGRESS_MODE) {
          // 普通模式下的错误处理
          setErrorMessage('连接超时,请检测输入信息是否正确后再试');
          setModalState(ModalState.FAILED);
        }
        // 进度版模式下的错误处理在轮询函数中处理
      },
    }
  );

  // 更新数据库连接
  const { runAsync: updateConnection, loading: updateLoading } = useRequest(
    async (data: UpdateConnectionRequest) => {
      if (!connection?.database_id) {
        throw new Error('缺少连接ID');
      }
      
      if (ENABLE_PROGRESS_MODE) {
        // 进度版模式
        const response = await nl2sqlService.updateConnectionProgress(connection.database_id, data);
        setTaskId(response.task_id);
        startProgressPolling(response.task_id);
        return response;
      } else {
        // 普通模式
        return await nl2sqlService.updateConnection(connection.database_id, data);
      }
    },
    {
      manual: true,
      onSuccess: (data) => {
        if (!ENABLE_PROGRESS_MODE) {
          // 普通模式下的成功处理
          setModalState(ModalState.SUCCESS);
          message.success('更新成功');
          handleClose();
          onSuccess?.();
        }
        // 进度版模式下的成功处理在轮询函数中处理
      },
      onError: (error) => {
        if (!ENABLE_PROGRESS_MODE) {
          // 普通模式下的错误处理
          setErrorMessage('更新失败,请检测输入信息是否正确后再试');
          setModalState(ModalState.FAILED);
        }
        // 进度版模式下的错误处理在轮询函数中处理
      },
    }
  );

  const handleInputChange = (field: keyof FormData, value: string | string[]) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (connectionError) {
      setConnectionError('');
    }
  };

  // 检查名称是否重复
  const isNameDuplicate = (name: string): boolean => {
    if (!connections || connections.length === 0) {
      return false;
    }

    // 编辑模式下，排除当前正在编辑的连接
    const currentConnectionId = connection?.database_id;
    const otherConnections = connections.filter((conn: ConnectionInfo) => conn.database_id !== currentConnectionId);

    return otherConnections.some((conn: ConnectionInfo) => conn.display_name === name);
  };

  // 获取名称校验错误信息
  const getNameValidationError = (name: string): string | null => {
    if (!name.trim()) {
      return null;
    }

    if (isNameDuplicate(name)) {
      return '该名称已存在，请使用其他名称';
    }

    return null;
  };

  // 模拟进度条
  const simulateProgress = () => {
    if (ENABLE_PROGRESS_MODE) {
      // 进度版模式：显示初始进度
      setProgressValue(10);
    } else {
      // 普通模式：模拟进度
      setProgressValue(0);
      const interval = setInterval(() => {
        setProgressValue((prev: number) => {
          if (prev >= 90) {
            clearInterval(interval);
            return 90;
          }
          return prev + 10;
        });
      }, 200);
      return interval;
    }
  };

  const handleNextStep = async () => {
    if (currentStep === 0) {
      // 验证必填字段
      const requiredFields = [
        formData.displayName,
        formData.dbType,
        formData.host,
        formData.port,
        formData.username,
        formData.password,
      ];

      if (requiredFields.some(field => !field)) {
        message.error('请填写所有必填字段');
        return;
      }

      if (formData.dbType === 'oracle' && !formData.database) {
        message.error('请输入接入的数据库');
        return;
      }

      // 验证名称是否重复
      const nameValidationError = getNameValidationError(formData.displayName);
      if (nameValidationError) {
        message.error(nameValidationError);
        return;
      }

      try {
        // 测试连接（编辑模式和新建模式都需要测试）
        await testConnection({
          db_type: formData.dbType,
          host: formData.host,
          port: parseInt(formData.port),
          username: formData.username,
          password: formData.password,
          database: formData.database || '',
        });

        // 获取数据库列表（编辑模式和新建模式都需要获取）
        if (formData.dbType !== 'oracle') {
          await getDatabases({
            db_type: formData.dbType,
            host: formData.host,
            port: parseInt(formData.port),
            username: formData.username,
            password: formData.password,
            database: formData.database || '',
          });
        }

        // 如果已选择数据库，则查询该数据库下的表
        if (formData.selectedDatabase || formData.database) {
          await getTables({
            db_type: formData.dbType,
            host: formData.host,
            port: parseInt(formData.port),
            username: formData.username,
            password: formData.password,
            database: formData.selectedDatabase || formData.database,
          });
        }

        if (formData.dbType === 'oracle' && formData.database) {
          handleInputChange('selectedDatabase', formData.database);
        }

        setCurrentStep(1);
      } catch (error) {
        // 错误已在 useRequest 中处理
      }
    } else {
      // 第二步：选择数据库和表
      if (!formData.selectedDatabase || formData.selectedTable.length === 0) {
        message.error('请选择数据库和表');
        return;
      }

      // 开始创建/更新连接流程
      setModalState(ModalState.LOADING);
      const progressInterval = ENABLE_PROGRESS_MODE ? null : simulateProgress();

      try {
        // 构建请求数据
        const requestData = {
          name: formData.displayName,
          intro: formData.description,
          type: '',
          vectorModel: 'bge-large-zh-v1.5',
          agentModel: 'Qwen2_5-14B-Instruct',
          app_id: appId,
          administrator: [],
          groupId: groupId || '',
          assessor: [],
          databaseInfo: {
            app_id: appId,
            display_name: formData.displayName,
            config: {
              db_type: formData.dbType,
              host: formData.host,
              port: parseInt(formData.port),
              username: formData.username,
              password: formData.password,
              database: formData.selectedDatabase,
            },
            description: formData.description,
            tables: formData.selectedTable,
          },
        };

        if (isEditMode) {
          // 编辑模式：调用更新接口
          await updateConnection(requestData);
        } else {
          // 新建模式：调用创建接口
          await createConnection(requestData);
        }

        if (!ENABLE_PROGRESS_MODE && progressInterval) {
          clearInterval(progressInterval);
          setProgressValue(100);
        }
      } catch (error) {
        if (!ENABLE_PROGRESS_MODE && progressInterval) {
          clearInterval(progressInterval);
        }
        // 错误已在 useRequest 中处理
      }
    }
  };

  const handlePreviousStep = () => {
    setCurrentStep(0);
  };

  const handleRetry = () => {
    // 停止轮询
    stopPolling();
    setTaskId('');
    resetTaskProgress();
    
    setModalState(ModalState.LOADING);
    setErrorMessage('');
    setProgressValue(0);
    handleNextStep();
  };

  const handleClose = () => {
    setCurrentStep(0);
    setModalState(ModalState.FORM);
    setProgressValue(0);
    setErrorMessage('');
    // 停止轮询
    stopPolling();
    setTaskId('');
    resetTaskProgress();
    // 根据当前模式重新设置表单数据
    setFormData(getInitialFormData());
    setDatabases([]);
    setTables([]);
    setConnectionError('');
    setShowPassword(false);
    onClose();
  };

  const handleDatabaseChange = async (database: string) => {
    handleInputChange('selectedDatabase', database);
    handleInputChange('selectedTable', []);

    if (database) {
      try {
        await getTables({
          db_type: formData.dbType,
          host: formData.host,
          port: parseInt(formData.port),
          username: formData.username,
          password: formData.password,
          database: database,
        });
      } catch (error) {
        // 错误已在 useRequest 中处理
      }
    }
  };

  const steps = [
    {
      title: '填写基础信息',
    },
    {
      title: '选择接入范围',
    },
  ];

  // 渲染不同状态的模态框内容
  const renderModalContent = () => {
    switch (modalState) {
      case ModalState.LOADING:
        return (
          <div className="flex flex-col items-center justify-center py-8">
            <div className="mb-4 w-full">
              <Progress
                percent={progressValue}
                showInfo={false}
                strokeColor="#1890ff"
              />
            </div>
            <div className="text-center">
              <div className="text-gray-600">
                {ENABLE_PROGRESS_MODE 
                  ? (isEditMode ? '数据更新中,请稍等...' : '数据学习中,请稍等...')
                  : (isEditMode ? '数据更新中,请稍等...' : '数据学习中,请稍等...')
                }
              </div>
              <div className="text-sm text-gray-400 mt-2">{Math.floor(progress)}%</div>
            </div>
          </div>
        );

      case ModalState.SUCCESS:
        return (
          <div className="flex flex-col items-center justify-center py-8">
            <CheckCircleOutlined className="text-6xl text-green-500 mb-4" />
            <div className="text-xl font-medium text-gray-900 mb-6">
              {isEditMode ? '更新成功' : '接入成功'}
            </div>
            <Button type="primary" onClick={handleClose}>
              完成
            </Button>
          </div>
        );

      case ModalState.FAILED:
        return (
          <div className="flex flex-col items-center justify-center py-8">
            <CloseCircleOutlined className="text-6xl text-red-500 mb-4" />
            <div className="text-xl font-medium text-gray-900 mb-2">
              {isEditMode ? '更新失败' : '创建失败'}
            </div>
            <div className="text-sm text-text-3 mb-6 text-center">{errorMessage}</div>
            <div className="flex gap-10">
              <Button onClick={handleClose}>取消</Button>
              <Button type="primary" onClick={handleRetry}>重试</Button>
            </div>
          </div>
        );

      default:
        return (
          <div className="flex flex-col">
            {/* 步骤指示器 */}
            <div className="mb-6">
              <Steps
                current={currentStep}
                items={steps}
                size="small"
              />
            </div>

            {/* 第一步：填写基础信息 */}
            {currentStep === 0 && (
              <div className="space-y-4">
                {/* 显示名称 */}
                <div>
                  <div className="mb-2 flex items-center">
                    <span className="text-text-4">显示名称</span>
                    <span className="ml-1 text-error">*</span>
                  </div>
                  <Input
                    placeholder="请输入名称"
                    value={formData.displayName}
                    disabled={isEditMode && !!formData.displayName}
                    onChange={(e) => handleInputChange('displayName', e.target.value)}
                    status={getNameValidationError(formData.displayName) ? 'error' : undefined}
                  />
                  {getNameValidationError(formData.displayName) && (
                    <div className="mt-1 text-xs text-error">
                      {getNameValidationError(formData.displayName)}
                    </div>
                  )}
                </div>

                {/* 描述 */}
                <div className="relative">
                  <div className="mb-2 text-text-4">描述</div>
                  {/* <TextArea
                    placeholder="请输入数据库描述"
                    value={formData.description}
                    onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => handleInputChange('description', e.target.value)}
                    rows={3}
                    maxLength={150}
                  /> */}
                  <TextArea
                    className="w-full resize-none rounded-lg border p-2 [-ms-overflow-style:none] [scrollbar-width:none] focus:border-[#D9D9D9] focus:outline-none"
                    placeholder="请输入数据库描述"
                    value={formData.description}
                    onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => handleInputChange('description', e.target.value)}
                    autoSize={{ minRows: 4, maxRows: 6 }}
                    maxLength={150}
                  />
                  <div className="pointer-events-none absolute bottom-2 right-2 text-[14px] text-[#A5A9BB]">
                    {formData.description.length || 0} / 150
                  </div>
                </div>

                {/* 数据源信息 */}
                <div className="mt-6">
                  <div className="mb-4 font-semibold text-[16px] text-text-4">数据源信息</div>

                  {/* 数据库类型 */}
                  <div className="mb-4">
                    <div className="mb-2 flex items-center">
                      <span className="text-text-4">数据库类型</span>
                      <span className="ml-1 text-error">*</span>
                    </div>
                    <Select
                      placeholder="请选择"
                      value={formData.dbType}
                      onChange={(value) => handleInputChange('dbType', value)}
                      options={dbTypeOptions}
                      disabled={isEditMode && !!formData.dbType}
                      className="w-full"
                    />
                  </div>

                  {/* 数据库连接信息 - 两行两列布局 */}
                  <div className="grid grid-cols-2 gap-4 mb-4">
                    {/* 第一行第一列：数据库地址Host */}
                    <div>
                      <div className="mb-2 flex items-center">
                        <span className="text-text-4">数据库地址Host</span>
                        <span className="ml-1 text-error">*</span>
                      </div>
                      <Input
                        placeholder="请输入数据库地址Host"
                        value={formData.host}
                        disabled={isEditMode && !!formData.host}
                        onChange={(e) => handleInputChange('host', e.target.value)}
                      />
                    </div>

                    {/* 第一行第二列：端口号 */}
                    <div>
                      <div className="mb-2 flex items-center">
                        <span className="text-text-4">端口号</span>
                        <span className="ml-1 text-error">*</span>
                      </div>
                      <Input
                        placeholder="请输入端口号"
                        value={formData.port}
                        disabled={isEditMode && !!formData.port}
                        onChange={(e) => handleInputChange('port', e.target.value)}
                      />
                    </div>

                    {/* 第二行第一列：用户名 */}
                    <div>
                      <div className="mb-2 flex items-center">
                        <span className="text-text-4">用户名</span>
                        <span className="ml-1 text-error">*</span>
                      </div>
                      <Input
                        placeholder="请输入用户名"
                        value={formData.username}
                        onChange={(e) => handleInputChange('username', e.target.value)}
                      />
                    </div>

                    {/* 第二行第二列：密码 */}
                    <div>
                      <div className="mb-2 flex items-center">
                        <span className="text-text-4">密码</span>
                        <span className="ml-1 text-error">*</span>
                      </div>
                      <Input
                        type={showPassword ? 'text' : 'password'}
                        placeholder="请输入密码"
                        value={formData.password}
                        onChange={(e) => handleInputChange('password', e.target.value)}
                        suffix={
                          <div
                            className="cursor-pointer"
                            onClick={() => setShowPassword(!showPassword)}
                          >
                            {showPassword ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                          </div>
                        }
                      />
                    </div>
                  </div>
                  {
                    formData.dbType === 'oracle' && (    
                    <div>
                      <div className="mb-2 flex items-center">
                        <span className="text-sm font-medium text-gray-700">接入的数据库</span>
                        <span className="ml-1 text-error">*</span>
                      </div>
                      <Input
                        placeholder="请输入接入的数据库"
                        value={formData.database}
                        onChange={(e) => handleInputChange('database', e.target.value)}
                        className="w-full"
                      />
                    </div>
                    )
                  }
                </div>
              </div>
            )}

            {/* 第二步：选择接入范围 */}
            {currentStep === 1 && (
              <div className="space-y-4">
                {/* 选择数据库 */}
                <div>
                  <div className="mb-2 flex items-center">
                    <span className="text-sm font-medium text-gray-700">选择接入的数据库</span>
                    <span className="ml-1 text-error">*</span>
                  </div>
                  <Select
                    placeholder="请选择"
                    value={formData.selectedDatabase}
                    onChange={handleDatabaseChange}
                    options={databases.map(db => ({ label: db, value: db }))}
                    loading={getDbLoading}
                    className="w-full"
                    disabled={formData.dbType === 'oracle'}
                  />
                </div>

                {/* 选择表 */}
                <div>
                  <div className="mb-2 flex items-center">
                    <span className="text-sm font-medium text-gray-700">选择要接入的数据库表</span>
                    <span className="ml-1 text-error">*</span>
                  </div>
                  <div className="flex gap-2">
                    <Select
                      mode="multiple"
                      placeholder="请选择要接入的数据库表"
                      value={formData.selectedTable}
                      onChange={(value) => handleInputChange('selectedTable', value)}
                      options={tables.map(table => ({ label: table, value: table }))}
                      loading={getTableLoading}
                      disabled={!formData.selectedDatabase}
                      className="flex-1"
                      maxTagCount="responsive"
                      showSearch
                      filterOption={(input, option) =>
                        String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                    />
                    <Button
                      type="default"
                      size="middle"
                      onClick={() => {
                        if (formData.selectedTable.length === tables.length) {
                          // 如果已全选，则取消全选
                          handleInputChange('selectedTable', []);
                        } else {
                          // 如果未全选，则全选
                          handleInputChange('selectedTable', tables);
                        }
                      }}
                      disabled={!formData.selectedDatabase || tables.length === 0}
                    >
                      {formData.selectedTable.length === tables.length ? '取消' : '全选'}
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>
        );
    }
  };

  // 根据状态确定按钮文本和操作
  const getModalConfig = () => {
    switch (modalState) {
      case ModalState.LOADING:
        return {
          title: isEditMode ? '编辑数据库连接' : '接入数据库',
          footer: null,
        };
      case ModalState.SUCCESS:
        return {
          title: isEditMode ? '编辑数据库连接' : '接入数据库',
          footer: null,
        };
      case ModalState.FAILED:
        return {
          title: isEditMode ? '编辑数据库连接' : '接入数据库',
          footer: null,
        };
      default:
        return {
          title: isEditMode ? '编辑数据库连接' : '接入数据库',
          footer: undefined,
          okText: currentStep === 0 ? '下一步' : (isEditMode ? '更新' : '接入'),
          cancelText: currentStep === 0 ? '取消' : '上一步',
          onOk: handleNextStep,
          onCancel: currentStep === 0 ? handleClose : handlePreviousStep,

        };
    }
  };

  const modalConfig = getModalConfig();

  return (
    <Modals
      open={open}
      title={modalConfig.title}
      onClose={handleClose}
      okText={modalConfig.okText}
      cancelText={modalConfig.cancelText}
      onOk={modalConfig.onOk}
      onCancel={modalConfig.onCancel}
      footer={modalConfig.footer}
      destroyOnHidden={true}
      width={600}
      confirmLoading={testLoading || createLoading || updateLoading}
      footerOkDisabled={testLoading || createLoading || updateLoading}
    >
      {renderModalContent()}
    </Modals>
  );
};

export default DatabaseAccessModal; 